from GUI import Ui_MainWidget
import typing
from openpyxl import load_workbook

from PyQt5.QtWidgets import QListWidgetItem, QWidget
from PyQt5 import QtCore

from XuanWuUDPControler import XuanWuUDPControler
from XuanwuUDPReceiver import XuanWuUDPReceiver

class MainWidget(QWidget):
    def __init__(self, parent: typing.Optional['QWidget'], flags: typing.Union[QtCore.Qt.WindowFlags, QtCore.Qt.WindowType]) -> None:
        super().__init__(parent=parent, flags=flags)
        self.__ui = Ui_MainWidget()
        self.__ui.setupUi(self)
        self.__xuanwuUDPControler = XuanWuUDPControler(self)
        self.__xuanwuUDPReceiver = XuanWuUDPReceiver(self)

        # Setup xlsx数据
        try:
            self.__dictPayload = dict()
            work_book_ = load_workbook(filename='commandList.xlsx')
            work_sheet_ = work_book_['Sheet1']
            max_row_ = work_sheet_.max_row
            max_column_ = 10
            for row_ in range(max_row_):
                key_ = work_sheet_.cell(row_+1, 1).value
                item_ = QListWidgetItem(key_)
                self.__ui.listWidget.addItem(item_)
                value_list_ = list()
                for column_ in range(max_column_):
                    if (column_ != 0):
                        value_list_.append(work_sheet_.cell(row_+1, column_+1).value)
                value_ = ','.join(value_list_)
                self.__dictPayload[key_] = value_
        # print(self.__dictPayload)
        except:
            pass

        # Setup UI
        self.__ui.pushButtonListen.setText('开始监听')

        # Setup SignalSlot
        self.__ui.listWidget.itemDoubleClicked.connect(self.__SlotListWidgetDoubleClicked)
        self.__xuanwuUDPReceiver.signalSendReceiveData.connect(self.__ui.textEdit.append)
        self.__ui.pushButtonListen.clicked.connect(self.__SlotPushButtonListenClicked)

        # Setup BeginData
        self.__ui.lineEditSendIP.setText('192.168.44.151')
        self.__ui.lineEditSendPort.setText('10001')
        self.__ui.lineEditReceiveIP.setText('192.168.44.179')
        self.__ui.lineEditReceivePort.setText('10001')
        
    def __SlotListWidgetDoubleClicked(self, item: QListWidgetItem) -> None:
        payload_ = self.__dictPayload.get(item.text(), 'None Valid Data')
        ip_setting_ = self.__ui.lineEditSendIP.text()
        port_setting_ = self.__ui.lineEditSendPort.text()
        self.__xuanwuUDPControler.CommandRequest(payload_, ip_setting_, port_setting_)

    def __SlotPushButtonListenClicked(self) -> None:
        if (self.__xuanwuUDPReceiver.isRunning()):
            self.__xuanwuUDPReceiver.terminate()
            self.__ui.pushButtonListen.setText('开始监听')
        else:
            self.__xuanwuUDPReceiver.SetBindIpAndPort(self.__ui.lineEditReceiveIP.text(), 
                self.__ui.lineEditReceivePort.text())
            self.__xuanwuUDPReceiver.start()
            self.__ui.pushButtonListen.setText('停止监听')